package com.mc.lp.view.controllers;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.mc.lp.database.service.handler.FormHandlerFactory;
import com.mc.lp.database.service.handler.constant.FormHandler;
import com.mc.lp.database.service.handler.constant.FormRequestType;
import com.mc.lp.database.service.handler.constant.IFormHandler;
import com.mc.lp.database.service.handler.exception.UIExceptionList;
import com.mc.lp.shared.vo.IValueObject;
/**
 * abstract controller for all the controllers exists in system.
 * @author deepak
 *
 */
abstract public class AbstractController<T extends IMCController> implements IMCController{
	@Resource
	public FormHandlerFactory formHandlerFactory;
	public Class<T> clazz;
	public Logger LOG =null;
	@SuppressWarnings("unchecked")
	public AbstractController(){
		Type type = getClass().getGenericSuperclass();
		ParameterizedType paramType = (ParameterizedType) type;
		clazz = (Class<T>) paramType.getActualTypeArguments()[0];
		setLogger();
	}
	
	private void setLogger(){
		LOG= Logger.getLogger(this.clazz);
	}

	public Logger getLOG() {
		return LOG;
	}

	public void setLOG(Logger lOG) {
		LOG = lOG;
	}

	public FormHandlerFactory getFormHandlerFactory() {
		return formHandlerFactory;
	}

	public void setFormHandlerFactory(FormHandlerFactory formHandlerFactory) {
		this.formHandlerFactory = formHandlerFactory;
	}
	
	/**
	 * @author deepak
	 * common to all request serving methods
	 * @param formRequestType
	 * @param vo
	 * @return
	 * @throws Exception
	 */
	protected IValueObject handleRequestFromUI(FormHandler handlerType,FormRequestType formRequestType, IValueObject vo) throws Exception{
		if(formRequestType==null)
			throw new RuntimeException("Form Handler Not Found");
		//get the form factory instance
		FormHandlerFactory formFactory= getFormHandlerFactory();
		//find handler w.r.t form request type
		IFormHandler<IValueObject, IValueObject> handler = formFactory.getHandler(handlerType,formRequestType);
		IValueObject response= null;
		try {
			response=handler.handleRequest(formRequestType, vo);
		} catch (UIExceptionList e) {
			throw e;
		}catch(Exception e){
			throw e;
		}
		return response;
	}
	
}
